package com.aniu.cameramanager;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;

import com.aniu.cameramanager.util.CameraUtil;
import com.aniu.cameramanager.util.WorkTime;

public class SettingsActivity extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = SettingsActivity.class.getSimpleName();

    private Button mBtnApply;
    private int amStartWorkTime, amStopWorkTime, pmStartWorkTime, pmStopWorkTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.settings, new SettingsFragment())
                .commit();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
//            actionBar.setDisplayShowHomeEnabled(false);
//            actionBar.setTitle("返回");
        }

        mBtnApply = findViewById(R.id.btn_apply);
        mBtnApply.setOnClickListener(this);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:   //返回键的id
                if (refreshAndCheckTime()) {
                    this.finish();
                    return false;
                }

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onStart() {
        refreshAndCheckTime();

        super.onStart();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_apply) {
            if (refreshAndCheckTime()) {
                CameraUtil.blockOrUnblockCameraNow(this, amStartWorkTime, amStopWorkTime, pmStartWorkTime, pmStopWorkTime);
                Log.i(TAG, "设置的工作时间段有效");
            }
        }
    }

    private boolean refreshAndCheckTime() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        amStartWorkTime = sharedPreferences.getInt(WorkTime.AM_START_WORK_KEY, WorkTime.AM_START_WORK_DEFAULT_TIME);
        amStopWorkTime = sharedPreferences.getInt(WorkTime.AM_STOP_WORK_KEY, WorkTime.AM_STOP_WORK_DEFAULT_TIME);
        pmStartWorkTime = sharedPreferences.getInt(WorkTime.PM_START_WORK_KEY, WorkTime.PM_START_WORK_DEFAULT_TIME);
        pmStopWorkTime = sharedPreferences.getInt(WorkTime.PM_STOP_WORK_KEY, WorkTime.PM_STOP_WORK_DEFAULT_TIME);

        if ((amStartWorkTime < amStopWorkTime) && (amStopWorkTime < pmStartWorkTime)
                && (pmStartWorkTime < pmStopWorkTime)) {
            return true;

        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder
                    .setTitle(getString(R.string.set_fail_title))
                    .setMessage(getString(R.string.set_fail_content))
                    .setPositiveButton(getString(R.string.set_fail_ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    })
                    .create().show();

            return false;
        }
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);

            getPreferenceScreen().addPreference(createTimePickerPreference("上午开始工作时间", "AM_START_WORK", 540));
            getPreferenceScreen().addPreference(createTimePickerPreference("上午结束工作时间", "AM_STOP_WORK", 720));
            getPreferenceScreen().addPreference(createTimePickerPreference("下午开始工作时间", "PM_START_WORK", 840));
            getPreferenceScreen().addPreference(createTimePickerPreference("下午结束工作时间", "PM_STOP_WORK", 1050));
        }

        private TimePickerPreference createTimePickerPreference(String title, String key, int defaultValue) {
            TimePickerPreference pref = new TimePickerPreference(requireActivity());
            pref.setTitle(title);
            pref.setEnabled(true);
            pref.setKey(key);
            pref.setDefaultValue(defaultValue);
            pref.setIconSpaceReserved(false);

            return pref;
        }

        @Override
        public void onDisplayPreferenceDialog(Preference preference) {
            if (preference instanceof TimePickerPreference) {
                TimePickerDialogFragmentCompat dialogFragmentCompat = TimePickerDialogFragmentCompat.newInstance(preference.getKey());
                dialogFragmentCompat.setTargetFragment(this, 0);
                dialogFragmentCompat.show(getFragmentManager(), TimePickerDialogFragmentCompat.FRAGMENT_TAG);
                return;
            }

            super.onDisplayPreferenceDialog(preference);
        }
    }
}